<?php
namespace Agent\Controller;

use Utuo\BackgroundController;
use Agent\Model\DistributionShopOrderModel;
use Agent\Model\DistributionShopRateModel;

class AgentOrderController extends BackgroundController {
    
    private $agentId = 0;
    
    private $status = array(
        '0' => '未结订单',
        '1' => '已结订单',
    );
    
    public function _initialize() {
        $this->agentId = I('agentId', 0, 'intval');
        if ( !$this->agentId ) {
            exit('请先选择结算的代理商');
        }
        $this->setControllerTitle('结算订单');
        $this->setActionTitle(array(
            'settleAccounts' => '订单列表',
        	'detials' => '订单详情',
        ), '', 'agentId='.$this->agentId);
        $this->setActionNav(array(
            'settleAccounts',
        ));
        foreach ( $this->status as $k => $v ) {
            $this->setLinkNav($v, __CONTROLLER__."/settleAccounts?status=".$k."&agentId=".$this->agentId);
        }
        $this->assign("agentId", $this->agentId);
    }
    
    /**
     * 订单列表(agentId的订单与需要通过agentId结算的订单)
     */
    public function settleAccountsAction() {
    	$statusArray = array(
    		'0' => '未结算',
    		'1' => '已结算'
    	);
        $status = I('status', 1, "intval"); // 0.未结订单 1.已结订单
        $startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
        $endDate = I('endDate', 0, 'intval') or $endDate = time();
        $params = array(
            'status' => $status,
        	'startDate' => $startDate,
        	'endDate' => $endDate,
        );
		$orderSettleAccountsList = $this->search($params);
		$this->assign("params", $params);
        $this->assign("orderSettleAccountsList", $orderSettleAccountsList);
        $this->assign("statusOptions", $this->getRadio("status", $statusArray, $status));
        $this->display();
    }
    
    
    /**
     * 查询
     * @param unknown $params
     * @return unknown
     */
    private function search( $params, $paginate = true ) {
        $type = $params['type'];
        $page = $this->getPage();
        $condition = array(
        	'a.end_agent' => $this->aid, // 发送给我的结算
            'a.status' => $params['status'], // 结算状态
            'b.deal_time' => array(array('egt', $params['startDate']), array('elt', $params['endDate']), 'and'),
        );
        $this->agentId and $condition['c.tree'] = array( // agentId参与的订单
        		'exp', "!='' and find_in_set({$this->agentId},c.tree)"
        );
        $m = M("DistributionShopOrderSettleAccounts a")->join("__DISTRIBUTION_SHOP_ORDER__ b on b.id = a.order_id", "left") // 连接订单数据
                                                       ->join("__AGENT__ c on c.id = b.agent_id", "left") // 连接订单的代理商信息 
                                                       ->where($condition);
        $n = clone $m;
        if( $paginate ) {
            $totalRows = $n->count();
            $m->page($page)->limit($this->getPageSize());
            $this->showPage($totalRows, $this->pageSize);
        }
        $productOrderGoodsLists = $m->field("b.*,a.id as settleId")->select();
        return $productOrderGoodsLists;
    }
    
    
    /**
     * 订单详细
     */
    public function detialsAction() {
    	$orderId = I("id", 0);
    	$order = $this->getOrder($orderId);
    	if ( $order['operate'] == 'deliver') {
    		$express = \Utuo\Express::getInstance();
    		$expressNames = $express->getExpressname();
    		$expressValues = array_values($expressNames);
    		$order['deliverMethodRadio'] = $this->getRadio("deliver_method", $this->deliverMethod, '0');
    		$order['expressOptions'] = $this->getOption(array_combine($expressValues, $expressValues), $order['express_name'], "====请选择快递====");
    	}
    	$this->assign("order", $order);
    	$this->display();
    }
    
    // 获得订单操作
    private function getOperate(&$v) {
    	if(($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SHIPPING)) $v['operate'] = "deliver";
    	if($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_COMPLETED and in_array($v['rate_status'], array(DistributionShopRateModel::RATE_STATUS_BUYER))) {
    		$v['operate'] = "check_comment";
    	}
    }
    
    /**
     * 获得一个订单
     * @param unknown $id
     * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
     */
    private function getOrder($id) {
    	$order = M ( "DistributionShopOrder orders" )->join( "__WECHAT_USER__ user on orders.uid=user.id", "LEFT")->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )->field ( "orders.*,user.nickname as userName,province.name as provinceName, city.name as cityName, area.name as areaName" )->where ( "orders.id=%d", $id )->find ();
    	if ( !$order ) return null;
    	$orders = array (
    			&$order
    	);
    	$this->bindOrderDetail ( $orders );
    	return $order;
    }
    
    /* 绑定订单详细 */
    private function bindOrderDetail(&$orderLists) {
    	/* 关联订单商品 */
    	$dProductOrder = D ( "Agent/DistributionShopOrder" );
    	$mProductGoods = M ( "DistributionShopOrderGoods" );
    	foreach ( $orderLists as &$v ) {
    		// 绑定显示状态
    		$v ["orderStatusName"] = $dProductOrder->getOrderShowStatus ( $v ['order_status'], $v ['pay_status'], $v ['shipping_status'] );
    		// 获得操作
    		$this->getOperate($v);
    		// 绑定订单商品
    		$orderGoods = $mProductGoods->where ( "order_id=%d", $v ['id'] )->select ();
    		foreach ( $orderGoods as &$v0 ) {
    			$v ['orderItems'] [$v0 ['product_id']] or $v ['orderItems'] [$v0 ['product_id']] = array (
    					'productId' => $v0 ['product_id'],
    					'productName' => $v0 ['product_name'],
    					'items' => array ()
    			);
    			$v ['orderItems'] [$v0 ['product_id']] ['items'] [] = array (
    					'productPic' => $v0 ['product_pic'],
    					'productNumber' => $v0 ['product_number'],
    					'productPrice' => $v0 ['product_price'],
    					'productAttr' => $v0 ['product_attr']
    			);
    		}
    	}
    }
    
}